<template>
    <div>
        <div>
            <a-form style="margin-top: 10px;margin-left: 5px;" :layout="'inline'">
                <a-form-item label="问题标题">
                    <a-input v-model:value="searchParams.title" placeholder="请输入问题标题" allowClear/>
                </a-form-item>
                <a-form-item label="发布人">
                    <a-select
                            v-model:value="searchParams.nickname"
                            size="middle"
                            style="width: 200px"
                            :options="userNicknameList"
                            placeholder="请选择发布人"
                    ></a-select>
                </a-form-item>
                <a-form-item label="最小浏览量">
                    <a-input v-model:value="searchParams.minViews" placeholder="请输入最小浏览量" allowClear/>
                </a-form-item>
                <a-form-item label="最大浏览量">
                    <a-input v-model:value="searchParams.maxViews" placeholder="请输入最大浏览量" allowClear/>
                </a-form-item>
                <a-form-item label="最小点赞数">
                    <a-input v-model:value="searchParams.minLikeCount" placeholder="请输入最小点赞数" allowClear/>
                </a-form-item>
                <a-form-item label="最大点赞数">
                    <a-input v-model:value="searchParams.maxLikeCount" placeholder="请输入最大点赞数" allowClear/>
                </a-form-item>
                <a-form-item label="最小回复数">
                    <a-input v-model:value="searchParams.minReply" placeholder="请输入最小回复数" allowClear/>
                </a-form-item>
                <a-form-item label="最大回复数">
                    <a-input v-model:value="searchParams.maxReply" placeholder="请输入最大回复数" allowClear/>
                </a-form-item>
                <a-form-item label="是否解决">
                    <a-select
                            ref="select"
                            v-model:value="searchParams.solve"
                            placeholder="请选择是否解决"
                            style="width: 150px"
                            allowClear
                    >
                        <a-select-option value="0">否</a-select-option>
                        <a-select-option value="1">是</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="请选择时间">
                    <a-range-picker v-model:value="searchParams.date" valueFormat="YYYY-MM-DD"/>
                </a-form-item>
                <a-form-item>
                    <a-button @click="search" type="primary">
                        <template #icon>
                            <SearchOutlined/>
                        </template>
                        搜索
                    </a-button>
                    <a-button @click="resetSearch" class="main_rest">
                        <template #icon>
                            <SyncOutlined/>
                        </template>
                        重置
                    </a-button>
                </a-form-item>
            </a-form>
            <div class="main_operation">
                <a-button @click="handleAdd" class="main_operation_item" type="primary">
                    新增
                    <template #icon>
                        <PlusOutlined/>
                    </template>
                </a-button>
                <a-button @click="handleEdit" :disabled="single" class="main_operation_edit">
                    <template #icon>
                        <EditTwoTone/>
                    </template>
                    修改
                </a-button>
                <a-button @click="handleDelete" :disabled="multiple" class="main_operation_item" type="primary" danger>
                    <template #icon>
                        <DeleteTwoTone/>
                    </template>
                    删除
                </a-button>
                <a-button @click="handleExportProblem" class="main_operation_export">
                    <template #icon>
                        <VerticalAlignBottomOutlined/>
                    </template>
                    导出
                </a-button>
            </div>
        </div>

        <a-table :row-selection="rowSelection" :columns="columns" :data-source="problemList" :pagination="pagination"
                 row-key="id" style="word-break: break-all;">
            <template v-slot:bodyCell="{ column, text, record }">
                <template v-if="column.dataIndex === 'avatar'">
                    <a-image :src="record.avatar" style="width: 130px;height: 130px;" alt="头像"/>
                </template>
                <template v-if="column.dataIndex === 'operation'">
                    <div>
          <span>
            <a-button @click="handleEdit(record.id)" class="main_operation_button" type="primary" ghost>修改</a-button>
            <a-button @click="handleDelete(record)" class="main_operation_button"
                      danger>删除</a-button>
          </span>
                    </div>
                </template>
            </template>
        </a-table>

        <!-- 新增或修改对话框 -->
        <a-modal
                ref="modalRef"
                v-model:visible="visible"
                @ok="handleOk"
                cancelText="取消"
                okText="确认"
        >
            <a-form :label-col="{ span: 4 }">
                <a-form-item label="问题标题" v-bind="validateInfos.title">
                    <a-input v-model:value="problem.title" placeholder="请输入问题标题"/>
                </a-form-item>
                <a-form-item label="发布人" v-bind="validateInfos.userId">
                    <a-input v-model:value="problem.userId" placeholder="请输入发布人"/>
                </a-form-item>
                <a-form-item label="发布人昵称" v-bind="validateInfos.nickname">
                    <a-input v-model:value="problem.nickname" placeholder="请输入发布人昵称"/>
                </a-form-item>
                <a-form-item label="发布人头像" v-bind="validateInfos.avatar">
                    <a-input v-model:value="problem.avatar" placeholder="请输入发布人头像"/>
                </a-form-item>
                <a-form-item label="浏览量">
                    <a-input v-model:value="problem.views" placeholder="请输入浏览量"/>
                </a-form-item>
                <a-form-item label="点赞数">
                    <a-input v-model:value="problem.likeCount" placeholder="请输入点赞数"/>
                </a-form-item>
                <a-form-item label="回复数">
                    <a-input v-model:value="problem.reply" placeholder="请输入回复数"/>
                </a-form-item>
                <a-form-item label="是否解决">
                    <a-radio-group v-model:value="problem.solve">
                        <a-radio :value="'0'">否</a-radio>
                        <a-radio :value="'1'">是</a-radio>
                    </a-radio-group>
                </a-form-item>
            </a-form>
            <template #title>
                <div ref="modalTitleRef" style="width: 100%; cursor: move">{{ title }}</div>
            </template>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import {Form, message, Modal, TableColumnType} from "ant-design-vue";
import {
    PlusOutlined,
    EditTwoTone,
    DeleteTwoTone,
    VerticalAlignBottomOutlined,
    SyncOutlined,
    SearchOutlined, FireTwoTone
} from '@ant-design/icons-vue';
import {createVNode, reactive, ref} from "vue";
import {
    addProblem,
    deleteProblem, exportProblem,
    getProblem,
    getProblemList,
    searchProblem,
    updateProblem
} from "@/api/answer/problem";
import {getUserNickname} from "@/api/user/user";

//用户昵称列表
const userNicknameList = ref<any>([])

//获取所有用户昵称
const handleUserNickname = () => {
    getUserNickname().then((res) => {
        userNicknameList.value = [...res.data.data.list].map((item) => ({value: item.toString()}))
    })
}

interface DataType {
    key: string;
    id: number;
}

//标签
const columns: TableColumnType<DataType>[] = [
    {
        title: '问题标题',
        align: "center",
        width: 200,
        dataIndex: 'title',
    },
    {
        title: '发布人昵称',
        align: "center",
        width: 150,
        dataIndex: 'nickname',
    },
    {
        title: '发布人头像',
        align: "center",
        width: 150,
        dataIndex: 'avatar',
    },
    {
        title: '浏览量',
        align: "center",
        dataIndex: 'views',
    },
    {
        title: '点赞数',
        align: "center",
        dataIndex: 'likeCount',
    },
    {
        title: '回复数',
        align: "center",
        dataIndex: 'reply',
    },
    {
        title: '是否解决',
        align: "center",
        dataIndex: 'solve',
        customRender: (text: any) => {
            return text.value === '0' ? '否' : '是';
        }
    },
    {
        title: '创建时间',
        align: "center",
        dataIndex: 'createTime',
    },
    {
        title: '更新时间',
        align: "center",
        dataIndex: 'updateTime',
    },
    {
        title: '操作',
        align: "center",
        dataIndex: 'operation',
    },
];

//选中的id数组
const ids = ref<number[]>([])
//非单个禁用
const single = ref<boolean>(true)
//是否多选
const multiple = ref<boolean>(true)

//多选框
const rowSelection = {
    onChange: (selectedRowKeys: string[], selectedRows: DataType[]) => {
        ids.value = selectedRows.map(item => item.id)
        single.value = ids.value.length !== 1
        multiple.value = !ids.value.length
    }
};

//是否显示修改对话框
const visible = ref<boolean>(false);
//对话框标题
const title = ref("")

//问题信息
const problem = ref({
    id: '',
    title: '',
    userId: '',
    nickname: '',
    avatar: '',
    views: 0,
    likeCount: 0,
    reply: 0,
    solve: 0,
})

//表单校验
const rulesRef = reactive({
    title: [
        {
            required: true,
            message: '请输入问题标题',
        }
    ],
    userId: [
        {
            required: true,
            message: '请输入发布人',
        }
    ],
    nickname: [
        {
            required: true,
            message: '请输入发布人昵称',
        }
    ],
    avatar: [
        {
            required: true,
            message: '请输入发布人头像',
        }
    ],
});

const useForm = Form.useForm;
const {validate, validateInfos} = useForm(problem, rulesRef);

//问题列表
const problemList = ref()

//分页参数
const pagination = ref({
    size: 'large',
    current: 1,
    pageSize: 10,
    total: 0,
    pageSizeOptions: ['10', '20', '30'],
    showTotal: (total: number) => {
        return " 共" + total + "条"
    },
    showSizeChanger: true,
    onShowSizeChange: (current: number, pageSize: number) => {
        pagination.value.pageSize = pageSize
        search()
    },
    onChange: (current: number) => {
        pagination.value.current = current
        search()
    }
})

//搜索参数
const searchParams = ref({
    title: '',
    nickname: null,
    minViews: '',
    maxViews: '',
    minLikeCount: '',
    maxLikeCount: '',
    minReply: '',
    maxReply: '',
    solve: null,
    startTime: '',
    endTime: '',
    date: null as any
})

//获取所有问题
const handleProblemList = () => {
    getProblemList(pagination.value.current, pagination.value.pageSize).then((res) => {
        problemList.value = res.data.data.map.list
        pagination.value.total = res.data.data.map.total
    })
}

//修改问题
const handleEdit = (id: number) => {
    reset()
    const problemId: any = ids.value[0] || id
    visible.value = true
    title.value = "修改问题信息"
    getProblem(problemId).then((res) => {
        problem.value = res.data.data.problem
    })
}

//新增问题
const handleAdd = () => {
    reset()
    title.value = "新增问题信息"
    visible.value = true
}

//删除问题
const handleDelete = (row: any) => {
    const problemIds: any = row.id || ids.value
    Modal.confirm({
        title: '你确定要删除这个问题吗?',
        icon: createVNode(FireTwoTone),
        okText: '确认',
        cancelText: '取消',
        onOk() {
            return new Promise((resolve, reject) => {
                setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
                deleteProblem(problemIds).then((res) => {
                    message.success(res.data.message)
                    handleProblemList()
                })
            }).catch(() => console.log('Oops errors!'));
        },
        onCancel() {
        },
    });
}

//新增或修改提交按钮
const handleOk = () => {
    validate().then(() => {
        if (problem.value.id != '') {
            updateProblem(problem.value).then((res) => {
                if (res.data.code === 400) {
                    message.warn(res.data.message)
                } else {
                    visible.value = false;
                    handleProblemList()
                }
            })
        } else {
            addProblem(problem.value).then((res) => {
                if (res.data.code === 400) {
                    message.warn(res.data.message)
                } else {
                    visible.value = false;
                    handleProblemList()
                }
            })
        }
    }).catch(err => {
        console.log('error', err);
    });
}

//对话框表单重置
const reset = () => {
    problem.value.id = ''
    problem.value.title = ''
    problem.value.userId = ''
    problem.value.nickname = ''
    problem.value.avatar = ''
    problem.value.views = 0
    problem.value.likeCount = 0
    problem.value.reply = 0
    problem.value.solve = 0
}

//搜索表单重置
const resetSearch = () => {
    searchParams.value.title = ''
    searchParams.value.nickname = null
    searchParams.value.minViews = ''
    searchParams.value.maxViews = ''
    searchParams.value.minLikeCount = ''
    searchParams.value.maxLikeCount = ''
    searchParams.value.minReply = ''
    searchParams.value.maxReply = ''
    searchParams.value.solve = null
    searchParams.value.startTime = ''
    searchParams.value.endTime = ''
    searchParams.value.date = null as any
    handleProblemList()
}

//搜索
const search = () => {
    if (searchParams.value.date != null) {
        searchParams.value.startTime = searchParams.value.date[0]
        searchParams.value.endTime = searchParams.value.date[1]
    }
    searchProblem(searchParams.value).then((res) => {
        problemList.value = res.data.data.list
        pagination.value.total = res.data.data.list.length
    })
}

//导出
const handleExportProblem = () => {
    exportProblem().then((response) => {
        message.success("导出成功")
        let blob = new Blob([response.data], {
            //要与后端对应
            type: 'application/vnd.ms-excel'
        });
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '问题列表.xlsx';
        link.click();
        //释放内存
        window.URL.revokeObjectURL(link.href)
    })
}

handleProblemList()
handleUserNickname()
</script>

<style lang="less" scoped>
.main_operation {
  margin: 10px;
  display: flex;

  .main_operation_item {
    margin-right: 10px;
  }

  .main_operation_edit {
    background-color: palegreen;
    margin-right: 10px;
  }

  .main_operation_export {
    background-color: sandybrown;
    margin-right: 10px;
  }
}

.main_rest {
  margin-left: 5px;
}

.main_operation_button {
  margin: 5px;
}

:deep(.ant-form-item-control-input-content) {
  margin-bottom: 5px;
}
</style>